package server

import (
	"encoding/json"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"server/src/global"
	"server/src/model"
	"server/src/model/request"
	"server/src/model/response"
	"time"
)

type groupUser struct {
}

// 获取用户积分
//func (u *user) GetUserIntegral(id int) (float64, error) {
//	user := &model.User{}
//	if err := global.GVL_DB.Where("id = ?", id).First(user).Error; err != nil {
//		return 0, err
//	}
//	return user.Integral, nil
//}

// 分页查找用户
func (u *groupUser) GetAllUserInfoPage(reqInfo *request.GetUserInfo, id int) (*response.GetAllUser, error) {
	resInfo := &response.GetAllUser{}
	var users []*model.WeChatGroupUser
	var err error
	db := global.GVL_DB.Model(&model.WeChatGroupUser{})
	resInfo.PageInfo, err = serverComment.getPageRes(*reqInfo.Page, db)
	if err != nil {
		fmt.Println("getPageRes设置出错", err)
		return nil, err
	}
	resInfo.PageInfo.PageReqInfo = *reqInfo.Page
	db = serverComment.paginate(*reqInfo.Page, db)
	if !(id == -1) {
		db.Where("gid = ?", id)
	} else if reqInfo.Gid != 0 {
		db.Where("gid = ?", reqInfo.Gid)
	}
	err = db.Where("name LIKE ?", "%"+reqInfo.Name+"%").Order("id desc").Find(&users).Error
	if err != nil {
		fmt.Println("find user设置出错", err)
		return nil, err
	}
	if !(id == -1) {
		resInfo.PageInfo.SumData = int64(len(users))
	} else if reqInfo.Gid != 0 {
		resInfo.PageInfo.SumData = int64(len(users))
	}
	resInfo.UsersInfo = users
	return resInfo, nil
}

// 分页查找用户积分记录
func (u *groupUser) GetAllUserIntegralInfoPage(reqInfo *request.GetUserIntegralInfoPage, id int) (*response.GetAllUserIntegral, error) {
	resInfo := &response.GetAllUserIntegral{}
	var division []model.DivisionRecord
	db := global.GVL_DB.Model(&model.DivisionRecord{})
	if !(id == -1) {
		db = db.Where("gid = ?", id)
	}
	var err error
	resInfo.PageInfo, err = serverComment.getPageRes(*reqInfo.Page, db)
	if err != nil {
		return nil, err
	}
	resInfo.PageInfo.PageReqInfo = *reqInfo.Page
	db = serverComment.paginate(*reqInfo.Page, db)

	err = db.Order("time desc").Find(&division).Error
	if err != nil {
		return nil, err
	}
	user := make([]*response.UsersIntegralInfo, len(division))
	for index, value := range division {
		user[index] = new(response.UsersIntegralInfo)
		user[index].UsersIntegralInfo = value
		username := &model.WeChatGroupUser{}
		err = global.GVL_DB.Model(&model.WeChatGroupUser{}).Where("id = ?", value.UserID).Take(username).Error
		if err != nil {
			fmt.Println("find user err :", err)
			continue
		}
		user[index].UserName = username.Name
		groupName := &model.WeChatGroup{}
		err = global.GVL_DB.Model(&model.WeChatGroup{}).Where("id = ?", username.Gid).Take(groupName).Error
		if err != nil {
			fmt.Println("find user err :", err)
			continue
		}
		user[index].GroupName = groupName.WeChatGroupName
	}
	resInfo.UserInfo = user
	return resInfo, nil
}

// 根据uid查看用户信息
func (g *groupUser) QueryGroupUserScore(uid int) *model.WeChatGroupUser {
	groupUserInfo := &model.WeChatGroupUser{}
	global.GVL_DB.Where("id = ?", uid).First(groupUserInfo)
	return groupUserInfo
}

// 用户查看本期下注数据
func (*groupUser) QueryBgCurrentBetting(uid, answerId int) (*response.OurBgCurrentBetting, error) {
	bgGuess := &model.BgGuess{}
	err := global.GVL_DB.Model(bgGuess).Where("user_id = ? and answer_id =?", uid, answerId).First(&bgGuess).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &response.OurBgCurrentBetting{}, nil
		}
		return nil, errors.New("bgGuess query error:" + err.Error())
	}
	bgGuessNums := make([]*model.BgGuessNum, 0)
	err = global.GVL_DB.Where("guess_id =?", bgGuess.Id).Order("time ASC").Find(&bgGuessNums).Error
	if err != nil {
		return nil, errors.New("bgGuessNums query error:" + err.Error())
	}

	//把查询的数据放入返回中
	oBgcurrentBetting := &response.OurBgCurrentBetting{
		Id:          bgGuess.Id,
		UserId:      uid,
		AnswerId:    answerId,
		BgGuessNums: make([]*response.BgGuessNum, 0),
	}
	for _, v := range bgGuessNums {
		newBgGuessNum := &response.BgGuessNum{
			GuessId:       bgGuess.Id,
			Integral:      v.Integral,
			PlayingMethod: v.PlayingMethod,
		}
		err = json.Unmarshal([]byte(v.Num), &newBgGuessNum.Num)
		if err != nil {
			return nil, errors.New("response json error:" + err.Error())
		}
		oBgcurrentBetting.BgGuessNums = append(oBgcurrentBetting.BgGuessNums, newBgGuessNum)
	}
	return oBgcurrentBetting, nil
}

// 用户申请上下方
func (*groupUser) ApplyDivision(uid int, gid int, integral float64) error {
	divisionRecord := &model.DivisionRecord{
		UserID:   uid,
		Gid:      gid,
		Division: integral,
		Status:   0,
		Time:     int(time.Now().Unix()),
	}
	tx := global.GVL_DB.Begin()
	if integral < 0 {
		err := tx.Model(&model.WeChatGroupUser{}).Where("id = ?", uid).
			Update("lower_division", gorm.Expr("lower_division + ?", integral)).Error
		if err != nil {
			tx.Rollback()
			return err
		}
	}
	err := tx.Create(divisionRecord).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	tx.Commit()
	return err
}

// 回水
func (*groupUser) GetReturnWater(userInfo *model.WeChatGroupUser) (float64, float64, error) {
	returnWater := userInfo.RunWater - userInfo.ReturnedWater
	returnWaterScore := returnWater * global.RETURNED_WATER
	err := global.GVL_DB.Model(&model.WeChatGroupUser{}).Where("id = ?", userInfo.Id).
		Updates(map[string]interface{}{"sum_score": gorm.Expr("sum_score + ?", returnWater),
			"system_score": gorm.Expr("system_score + ?", returnWaterScore), "returned_water": userInfo.RunWater}).Error
	//机器人回水数
	global.GVL_DB.Model(&model.WeChatGroup{}).Where("id = ?", userInfo.Gid).
		Updates(map[string]interface{}{"sum_score": gorm.Expr("returned_water + ?", returnWater)})
	if err != nil {
		return 0, 0, err
	}
	return returnWaterScore, userInfo.RunWater * global.RETURNED_WATER, nil
}

// 获取每个群中用户下注的信息
func (*groupUser) GetGroupUserCurrentBettingInfo(gid, answerId int) []*response.GetOneGroupBgCurrentBetting {
	var reqInfo []*response.GetOneGroupBgCurrentBetting
	global.GVL_DB.Model(&model.WeChatGroupUser{}).Joins("JOIN bg_guess ON we_chat_group_user.id = bg_guess.user_id").
		Select("bg_guess.*,we_chat_group_user.*").
		Where("bg_guess.answer_id = ? AND we_chat_group_user.gid = ?", answerId, gid).Find(&reqInfo)
	return reqInfo
}

// 清空用户的流水抽水和上下分
func (*groupUser) ClearUserTodayWater() {
	global.GVL_DB.Model(&model.WeChatGroupUser{}).Updates(map[string]interface{}{
		"run_water": 0, "returned_water": 0, "upward_division": 0, "lower_division": 0,
	})
}

// 查看每个群中用户不为0的积分
func (*groupUser) QueryUserScoreNotZero(gid int) []*model.WeChatGroupUser {
	var userInfos []*model.WeChatGroupUser
	global.GVL_DB.Model(&model.WeChatGroupUser{}).
		Where("gid = ? AND (sum_score !=0 OR upward_division != 0)", gid).
		Find(&userInfos)
	return userInfos
}
